<?php

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Validator;
use Illuminate\Http\Request;
use App\Models\Goods;
use App\Models\Category;
use App\Models\Attribute;
use Illuminate\Support\Facades\DB;

class GoodsController extends Controller {

    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index() {
        return Admin::content(function (Content $content) {

//                    $content->header('header');
//                    $content->description('description');
//
//                    $content->body($this->grid());
                    $content->header('Dashboard');
                    $content->description('Description...');
                    $content->body($this->grid());
                });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id) {
        return Admin::content(function (Content $content) use ($id) {

                    $content->header('header');
                    $content->description('description');

                    $content->body($this->form()->edit($id));
                });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create() {
        //return view('goods.index');
        return Admin::content(function (Content $content) {

                    $content->header('header');
                    $content->description('description');

                    //$content->body($this->form());
                    $content->row(view('goods.index', ['categoriesOptions' => Category::selectOptions()]));
                });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid() {
        return Admin::grid(Goods::class, function (Grid $grid) {
                    $grid->id('ID')->sortable();
                    $grid->name('名称');
                    $grid->desc('描述');
                    $grid->img_urls('图片')->image(env('APP_URL') . '/', 60, 60);
                    $grid->price('价格')->display(function($price) {
                        return $price . '元';
                    });
                    $grid->attribute('属性');
                    $grid->category()->title('分类');
                    $grid->created_at();
                    $grid->updated_at();
                });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form() {
        return Admin::form(Goods::class, function (Form $form) {
                    $form->display('id', 'ID');
                    $form->text('name', '名称')->rules('required');
                    $form->textarea('desc', '描述')->rules('required');
                    $form->multipleImage('img_urls', '图片')->removable();
                    //$form->html(view('goods.index'), '商品规格');
                    //$form->currency('price', '价格')->symbol('￥');
                    $form->select('category_id', '分类名称')->options(Category::selectOptions());
                    $form->textarea('attribute', '商品属性')->rules('required');
                    $form->editor('detail', '详情');
                    $form->display('created_at', 'Created At');
                    $form->display('updated_at', 'Updated At');
                    $form->saving(function (Form $form) {
                        $form->price = $form->price * 100;
                    });
                });
    }

    public function store(Request $request) {
        $input = $request->all();
        dd($input);
        $messages = [
            'name.required' => '请填写商品名称',
            'desc.required' => '请填写商品描述',
            'img_urls.required' => '请选择商品图片',
            'category_id.required' => '请选择商品分类',
            'detail.required' => '请填写商品详细',
        ];
        $validator = Validator::make($input, [
                    'name' => 'required',
                    'desc' => 'required',
                    'img_urls' => 'required',
                    'category_id' => 'required',
                    'detail' => 'required',
                        ], $messages);
//        if ($validator->fails()) {
//            $errors = $validator->errors()->all();
//            return response()->json([
//                        'status' => false,
//                        'message' => $errors[0],
//            ]);
//        }
        DB::beginTransaction();
        try {
            $goods = Goods::create([
                        'name' => $input['name'],
                        'desc' => $input['desc'],
                        'category_id' => $input['category_id'],
                        'detail' => $input['detail'],
            ]);
            $attrNames = $request->input('attr_name');
            $attrValues = $request->input('attr_value');
            $attribute = [];
            if (is_array($attrValues)) {
                foreach ($attrValues as $key => $attrValue) {
                    foreach ($attrValue as $v) {
                        $attribute[] = [
                            'name' => $attrNames[$key],
                            'value' => $v,
                            'goods_id'=>$goods->id,
                            //todo
                        ];
                    }
                }
            }

            Attribute::create([
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                        'status' => false,
                        'message' => $e->getMessage(),
            ]);
        }

        if ($images = $request->file('img_urls')) {
            if (config('admin.upload.disk') == 'qiniu') {
                foreach ($images as $image) {
                    $fileName = md5_file($image) . '.' . $image->extension();
                    $dir = config('admin.upload.directory.image');
                    $path = \Storage::disk('qiniu')->putFileAs(
                            $dir, $image, $fileName
                    );
                    dd($path);
                }
            }
        }

        dd($input);
        $input = Input::all();

        dd(Input::all());
        admin_toastr(trans('admin.save_succeeded'));
        return redirect('/admin/goods');
    }

}
